package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishExistException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class DishServiceImpl implements DishService {

    private final DishMapper dishMapper;

    private final DishFlavorMapper dishFlavorMapper;

    private final SetmealDishMapper setmealDishMapper;

    private final SetmealMapper setmealMapper;

    private final RedisTemplate redisTemplate;

    @Transactional
    @Override
    public void create(DishDTO dishDTO) {
        Integer count = dishMapper.selectDishByName(dishDTO.getName());
        if (count > 0){
            throw new DishExistException(MessageConstant.REPEAT_DISH_NAME);
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.insertDish(dish);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollectionUtils.isNotEmpty(flavors)){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
        redisTemplate.delete(getCacheKey(dishDTO.getCategoryId()));
    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        Dish dishquery = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO,dishquery);
        List<Dish> dishList = dishMapper.selectList(dishquery);

        PageInfo<Dish> pageInfo = new PageInfo<>(dishList);

        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    @Transactional
    public void delete(List<Long> ids) {

        Integer countByIdsAndStatus = dishMapper.selectCountByIdsAndStatus(ids);
        if (countByIdsAndStatus > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        Integer countByDishIds = setmealDishMapper.selectCountByDishIds(ids);
        if (countByDishIds > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        dishMapper.deleteDishByIds(ids);
        dishFlavorMapper.deleteDishFlavorByIds(ids);
    }

    @Override
    public DishVO selectById(Long id) {
        Dish dish = dishMapper.selectById(id);
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateDish(dish);

        dishFlavorMapper.deleteDishFlavorByIds(Collections.singletonList(dishDTO.getId()));
        createBatchDishFlavor(dishDTO,dish);
        redisTemplate.delete(getCacheKey(dishDTO.getCategoryId()));
    }

    @Transactional
    @Override
    public void changeStatus(Long id, Integer status) {
        Dish dish = dishMapper.selectById(id);
        dish.setStatus(status);
        dishMapper.updateDish(dish);
        if (Objects.equals(status, StatusConstant.DISABLE)) {
            List<Setmeal> setmealList = setmealDishMapper.selectSetmealDishByDishId(id);
            setmealList.forEach(setmeal -> {
                if (!Objects.equals(setmeal.getStatus(), StatusConstant.DISABLE)) {
                    setmeal.setStatus(StatusConstant.DISABLE);
                    setmealMapper.update(setmeal);
                }
            });
        }
        redisTemplate.delete(getCacheKey(dish.getCategoryId()));
    }

    @Override
    public List<Dish> selectByCategoryId(Long categoryId) {
        List<Dish> dishList = dishMapper.selectByCategoryId(categoryId);
        return dishList;
    }

    @Override
    public List<DishVO> selectDishVOByCategoryId(Long categoryId) {
        long startCache = System.currentTimeMillis();
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String cacheKey = getCacheKey(categoryId);
        String vos = (String)valueOperations.get(cacheKey);
        if (StringUtils.hasText(vos)){
            //缓存命中
            List<DishVO> dishVOList = JSON.parseArray(vos, DishVO.class);
            long endCache = System.currentTimeMillis();
            log.info("缓存消耗：{}", endCache - startCache);
            return dishVOList;
        }
        //缓存未命中，走数据库
        long startMySQL = System.currentTimeMillis();
        List<Dish> dishList = dishMapper.selectByCategoryId(categoryId);
        List<DishVO> dishVOList =
        dishList.stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            dishVO.setFlavors(dishFlavorMapper.selectByDishId(dish.getId()));
            return dishVO;
        }).collect(Collectors.toList());
        long endMySQL = System.currentTimeMillis();
        log.info("数据库消耗：{}", endMySQL - startMySQL);

        //放进redis中 - json
        valueOperations.set(cacheKey,JSON.toJSONString(dishVOList));
        return dishVOList;
    }

    private String getCacheKey(Long categoryId) {
        return "DISH_BY_CATEGORY_ID:" + categoryId;
    }


    private void createBatchDishFlavor(DishDTO dishDTO, Dish dish) {
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollectionUtils.isNotEmpty(flavors)){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
        }
    }
}
